package com.pw.demo3.service.impl;


import com.pw.demo3.annotation.PerAnnotion;
import com.pw.demo3.bean.Permission;
import com.pw.demo3.mapper.PermissionMapper;
import com.pw.demo3.service.PermissionService;
import com.sun.xml.internal.ws.model.ReflectAnnotationReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public int deleteByPrimaryKey(Long id) {
        return permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Permission record) {
        return permissionMapper.insert(record);
    }

    @Override
    public Permission selectByPrimaryKey(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Permission> selectAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(Permission record) {
        return permissionMapper.updateByPrimaryKey(record);
    }

    @Override
    public int reSet() {
        List<String> permissionsExp=permissionMapper.getAllExp();
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(Controller.class);
        Collection<Object> controllers = beansWithAnnotation.values();

        for (Object controller : controllers) {
            Method[] methods = controller.getClass().getDeclaredMethods();
            for (Method method:methods){
                // 判断方法上是否有指定注解：@RequiredPermission()
                if (method.isAnnotationPresent(PerAnnotion.class)){
                    // 获取方法上的注解
                    PerAnnotion annotation = method.getAnnotation(PerAnnotion.class);
                    // 获取方法中的参数
                    String name = annotation.name();
                    String expression = annotation.expression();
                    //判断表达式是否已在数据库
                    if (!permissionsExp.contains(expression)){
                        //保存数据
                        Permission permission = new Permission();
                        permission.setName(name);
                        permission.setExpression(expression);
                        permissionMapper.insert(permission);
                    }
                }
            }
        }
        return 0;
    }

    @Override
    public List<String> selectAllExp() {
        return permissionMapper.selectAllExp();
    }
}